package com.unicdata.ai.demo_2af.common.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * 加解密工具
 *
 * @author lhn
 * @date 2025/06/26 15:26
 * @since 1.0.0
 **/
public class AesEncryptUtils {

    private static final String AES_KEY = "MySecretKey12345"; // 生产中请放配置或密钥服务中
    private static final String ALGORITHM = "AES";

    private static final String ENCRYPT_PREFIX = "ENC:";


    public static String encrypt(String data) {
        if (data == null) return null;
        try {
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(AES_KEY.getBytes(StandardCharsets.UTF_8), ALGORITHM));
            byte[] result = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
            return ENCRYPT_PREFIX + Base64.getEncoder().encodeToString(result);
        } catch (Exception e) {
            throw new RuntimeException("加密失败", e);
        }
    }

    public static String decrypt(String data) {
        if (data == null) return null;
        if (!data.startsWith(ENCRYPT_PREFIX)) {
            return data;  // 如果没有前缀，说明不是加密数据
        }
        try {
            String encryptedData = data.substring(ENCRYPT_PREFIX.length());
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(AES_KEY.getBytes(StandardCharsets.UTF_8), ALGORITHM));
            byte[] result = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
            return new String(result, StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw new RuntimeException("解密失败", e);
        }
    }

}